
#include <vector>
#include "Pthread.hpp"

using namespace ThreadMoudle;
#define NUM 4

//pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;//定义全局的锁
pthread_spinlock_t lock;//自旋锁
int ticketnum = 10000;
void Ticket()
{
    while(true)
    {   
        //pthread_mutex_lock(&lock);//加锁
        pthread_spin_lock(&lock);
        if(ticketnum > 0)
        {
            usleep(100);
            //1.抢票
            printf("get a new ticket, id: %d\n",ticketnum--);
            //2.入库模拟  
            //usleep(1000);
            //pthread_mutex_unlock(&lock);//解锁
            pthread_spin_unlock(&lock);
        }
        else   
        {
            //pthread_mutex_unlock(&lock);//解锁
            pthread_spin_unlock(&lock);
            break;
        }
       
    }
}
int main()
{
    pthread_spin_init(&lock,PTHREAD_PROCESS_PRIVATE);//表示只在当前进程内部的线程使用
    std::vector<Thread> threads;
    for(int i = 0; i < NUM; i++)
    {
        threads.emplace_back(Ticket);
    }
    for(auto& thread : threads)
    {
        thread.Start();
    }

    for(auto& thread : threads)
    {
        thread.Join();
    }
    pthread_spin_destroy(&lock);
    return 0;
}
